import { useEffect, useState } from 'react'
import { TinyStore } from './TinyStore'

export function createGlobalStore<T>(instance: TinyStore<T>) {
  return function useStoreState<D>(getter: (state: T) => D): D {
    const [state, setState] = useState(getter(instance.getState()))
    useEffect(() => {
      return instance.subscript((formData) => {
        setState(getter(formData))
      })
    }, [getter])
    return state
  }
}
